package com.lmt.controller;

import com.lmt.entity.User;
import com.lmt.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

/**
 * 用户Controller
 * Date 2018/07/03
 *
 * @author MT-Lin
 */
@RestController
public class UserController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private final UserRepository userRepository;

    @Autowired
    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @GetMapping("/findUserById")
    public User findUserById(@RequestParam(name = "id") String id){
        Optional<User> optionalUser = userRepository.findById(id);
        logger.warn("simple-provider->findUserById:{}", optionalUser.orElse(null));
        return optionalUser.orElse(null);
    }

    @PostMapping("/saveUser")
    public User saveUser(@RequestBody User user){
        User userSaved = userRepository.save(user);
        logger.warn("simple-provider->saveUser:{}", userSaved);
        return userSaved;
    }

    @RequestMapping("/updateUser")
    public User updateUser(String id){
        Optional<User> optionalUser = userRepository.findById(id);
        logger.warn("simple-provider->updateUser:{}", optionalUser.orElse(null));
        assert optionalUser.orElse(null) != null;
        optionalUser.orElse(null).setUserName("update");
        User update = userRepository.save(optionalUser.orElse(null));
        logger.warn("simple-provider->updateUser:{}", update);
        return update;
    }
}
